<template>
  <view>
    <s-layout :onShareAppMessage="shareInfo" navbar="goods">
      <!-- 标题栏 -->
      <!-- <coachNavbar /> -->

      <!-- 骨架屏 -->
      <!-- <coachSkeleton v-if="state.skeletonLoading" /> -->
      <!-- 下架/不可用提醒 -->
      <s-empty
        v-if="state.coachInfo === null"
        text="教练不存在或已下架"
        icon="/static/soldout-empty.png"
        showAction
        actionText="再看看"
        actionUrl="/pages/index/index"
      />
      <block v-else>
        <view class="detail-swiper-selector">
          <!-- 教练轮播图  -->
          <su-swiper
            class="ss-m-b-14"
            isPreview
            :list="formatGoodsSwiper(state.coachInfo.sliderPicUrls)"
            otStyle="tag"
            imageMode="widthFix"
            dotCur="bg-mask-40"
            :seizeHeight="750"
          />

          <!-- 教练信息卡片 -->
          <view class="coach-card detail-card ss-p-y-30 ss-p-x-20">
            <view class="ss-flex ss-row-between ss-col-center ss-m-b-26">
              <view class="coach-info ss-flex ss-col-center">
                <image class="coach-avatar" :src="sheep.$url.cdn(state.coachInfo.picUrl)" />
                <view class="coach-details ss-m-l-20">
                  <view class="coach-name">{{ state.coachInfo.name }}</view>
                  <view class="coach-experience">{{ state.coachInfo.introduction }}</view>
                  <view class="coach-rating ss-flex ss-col-center ss-m-t-10">
                    <view class="rating-stars ss-flex ss-col-center">
                      <text class="star-icon" v-for="i in 5" :key="i"
                        :class="{ 'active': i <= Math.floor(5) }">★</text>
                    </view>
                    <text class="rating-text ss-m-l-10">5.0分</text>
                   <!-- <text class="student-count ss-m-l-20">已带学员{{ formatSales('exact', state.coachInfo.salesCount) }}</text> -->
                  </view>
                </view>
              </view>
              <view class="price-box ss-flex ss-col-bottom">
                <view class="price-text ss-m-r-16">
                  {{ fen2yuan(state.selectedSku.price || state.coachInfo.price) }}
                </view>
                <view class="price-unit">/课时</view>
              </view>
            </view>

            <!-- 教练标签 -->
            <view class="coach-tags ss-flex ss-m-b-20">
              <view class="tag">经验丰富</view>
              <view class="tag">通过率高</view>
              <view class="tag">耐心细致</view>
              <view class="tag">因材施教</view>
            </view>

            <!-- 优惠信息 -->
            <view class="discounts-box ss-flex ss-row-between ss-m-b-28">
              <view
                class="tag ss-m-r-10"
                v-for="coupon in state.couponInfo.slice(0, 1)"
                :key="coupon.id"
                @tap="onOpenActivity"
              >
                [券]满{{ fen2yuanSimple(coupon.usePrice) }}元{{
                  coupon.discountType === 1
                    ? '减' + fen2yuanSimple(coupon.discountPrice) + '元'
                    : '打' + formatDiscountPercent(coupon.discountPercent) + '折'
                }}
              </view>
              <view
                class="get-coupon-box ss-flex ss-col-center ss-m-l-20"
                @tap="onOpenActivity"
                v-if="state.couponInfo.length"
              >
                <view class="discounts-title ss-m-r-8">领券</view>
                <text class="cicon-forward"></text>
              </view>
            </view>
          </view>

          <!-- 功能卡片 -->
          <view class="detail-cell-card detail-card ss-flex-col">
            <coachCellSku
              v-model="state.selectedSku.goods_sku_text"
              :sku="state.selectedSku"
              @tap="state.showTimeSelect = true"
            />
          </view>

          <!-- 预约时间选择弹框 -->
          <su-popup
            :show="state.showTimeSelect"
            type="bottom"
            round="20"
            :isMaskClick="true"
            @close="state.showTimeSelect = false"
          >
            <view class="time-select-popup">
              <view class="popup-header ss-flex ss-row-between ss-col-center ss-p-x-30 ss-p-y-20">
                <text class="popup-title">选择预约时间</text>
                <text class="close-btn" @tap="state.showTimeSelect = false">✕</text>
              </view>
              <view class="time-content ss-p-30">
                <view class="date-selector ss-m-b-30">
                  <view class="date-title ss-m-b-20">选择日期</view>
                  <scroll-view class="date-scroll" scroll-x>
                    <view class="date-list ss-flex">
                      <view
                        v-for="(date, index) in state.availableDates"
                        :key="index"
                        class="date-item"
                        :class="{ 'active': state.selectedDate === date.value }"
                        @tap="selectDate(date.value)"
                      >
                        <view class="date-day">{{ date.day }}</view>
                        <view class="date-date">{{ date.date }}</view>
                      </view>
                    </view>
                  </scroll-view>
                </view>

                <view class="time-selector">
                  <view class="time-title ss-m-b-20">选择时间</view>
                  <view class="time-grid">
                    <view
                      v-for="time in state.availableTimes"
                      :key="time"
                      class="time-item"
                      :class="{ 'active': state.selectedTime === time, 'disabled': isTimeDisabled(time) }"
                      @tap="selectTime(time)"
                    >
                      {{ time }}
                    </view>
                  </view>
                </view>

                <button
                  class="confirm-btn ss-m-t-40"
                  :disabled="!state.selectedDate || !state.selectedTime"
                  @tap="confirmBooking"
                >
                  确认预约
                </button>
              </view>
            </view>
          </su-popup>
        </view>

        <!-- 评价 -->
        <coachCommentCard class="detail-comment-selector" :coachId="state.coachId" />
        <!-- 详情 -->
        <coachContentCard
          class="detail-content-selector"
          :content="state.coachInfo.description"
        />

        <!-- 详情 tabbar -->
        <coachTabbar v-model="state.coachInfo">
          <view class="buy-box ss-flex ss-col-center ss-p-r-20">
            <button
              class="ss-reset-button booking-btn ui-Shadow-Main"
              @tap="state.showTimeSelect = true"
            >
              立即预约
            </button>
          </view>
        </coachTabbar>

        <!-- 预约时间选择弹窗 -->
        <su-popup
          :show="state.showTimeSelect"
          type="bottom"
          round="20"
          :isMaskClick="true"
          @close="state.showTimeSelect = false"
        >
          <view class="time-select-popup">
            <view class="popup-header ss-flex ss-row-between ss-col-center ss-p-x-30 ss-p-y-20">
              <text class="popup-title">选择预约时间</text>
              <text class="close-btn" @tap="state.showTimeSelect = false">✕</text>
            </view>
            <view class="time-content ss-p-30">
              <view class="date-selector ss-m-b-30">
                <view class="date-title ss-m-b-20">选择日期</view>
                <scroll-view class="date-scroll" scroll-x>
                  <view class="date-list ss-flex">
                    <view
                      v-for="(date, index) in state.availableDates"
                      :key="index"
                      class="date-item"
                      :class="{ 'active': state.selectedDate === date.value }"
                      @tap="selectDate(date.value)"
                    >
                      <view class="date-day">{{ date.day }}</view>
                      <view class="date-date">{{ date.date }}</view>
                    </view>
                  </view>
                </scroll-view>
              </view>

              <view class="time-selector">
                <view class="time-title ss-m-b-20">选择时间</view>
                <view class="time-grid">
                  <view
                    v-for="time in state.availableTimes"
                    :key="time"
                    class="time-item"
                    :class="{ 'active': state.selectedTime === time, 'disabled': isTimeDisabled(time) }"
                    @tap="selectTime(time)"
                  >
                    {{ time }}
                  </view>
                </view>
              </view>

              <button
                class="confirm-btn ss-m-t-40"
                :disabled="!state.selectedDate || !state.selectedTime"
                @tap="confirmBooking"
              >
                确认预约
              </button>
            </view>
          </view>
        </su-popup>

        <!-- 详情 tabbar -->
        <coachTabbar v-model="state.coachInfo">
          <view class="buy-box ss-flex ss-col-center ss-p-r-20">
            <button
              class="ss-reset-button booking-btn ui-Shadow-Main"
              @tap="state.showTimeSelect = true"
            >
              立即预约
            </button>
          </view>
        </coachTabbar>

        <!-- 优惠券弹窗 -->
        <s-activity-pop
          v-model="state"
          :show="state.showActivityModel"
          @close="state.showActivityModel = false"
          @get="onTakeCoupon"
        />
      </block>
    </s-layout>
  </view>
</template>

<script setup>
  import { reactive, computed } from 'vue';
  import { onLoad, onPageScroll } from '@dcloudio/uni-app';
  import sheep from '@/sheep';
  import CouponApi from '@/sheep/api/promotion/coupon';
  import FavoriteApi from '@/sheep/api/product/favorite';
  import {
    formatSales,
    formatGoodsSwiper,
    fen2yuan,
    fen2yuanSimple,
    formatDiscountPercent,
  } from '@/sheep/hooks/useGoods';
  import coachNavbar from './components/coach-navbar.vue';
  import coachCellSku from './components/coach-cell-sku.vue';
  import coachTabbar from './components/coach-tabbar.vue';
  import coachSkeleton from './components/coach-skeleton.vue';
  import coachCommentCard from './components/coach-comment-card.vue';
  import coachContentCard from './components/coach-content-card.vue';
  import { isEmpty } from 'lodash-es';
  import SpuApi from '@/sheep/api/product/spu';
  import { SharePageEnum } from '@/sheep/helper/const';

  onPageScroll(() => {});

  const isLogin = computed(() => sheep.$store('user').isLogin);
  const state = reactive({
    coachId: 0,
    skeletonLoading: true,
    coachInfo: {},
    showTimeSelect: false,
    selectedSku: {},
    couponInfo: [],
    showActivityModel: false,
    selectedDate: '',
    selectedTime: '',
    availableDates: [],
    availableTimes: [
      '09:00', '10:00', '11:00', '14:00', '15:00', '16:00', '17:00', '18:00'
    ],
  });

  // 生成可预约日期（今天到未来30天）
  const generateAvailableDates = () => {
    const dates = [];
    const today = new Date();

    for (let i = 0; i < 31; i++) {
      const date = new Date(today);
      date.setDate(today.getDate() + i);

      const dayNames = ['周日', '周一', '周二', '周三', '周四', '周五', '周六'];
      const month = date.getMonth() + 1;
      const day = date.getDate();

      dates.push({
        value: `${date.getFullYear()}-${month.toString().padStart(2, '0')}-${day.toString().padStart(2, '0')}`,
        day: i === 0 ? '今天' : dayNames[date.getDay()],
        date: `${month}/${day}`
      });
    }

    state.availableDates = dates;
  };

  // 选择日期
  const selectDate = (date) => {
    state.selectedDate = date;
    state.selectedTime = ''; // 重置时间选择
  };

  // 选择时间
  const selectTime = (time) => {
    if (isTimeDisabled(time)) return;
    state.selectedTime = time;
  };

  // 判断时间是否可选
  const isTimeDisabled = (time) => {
    if (!state.selectedDate) return true;

    const today = new Date();
    const selectedDate = new Date(state.selectedDate);

    // 如果是今天，过滤掉已过去的时间
    if (selectedDate.toDateString() === today.toDateString()) {
      const currentHour = today.getHours();
      const timeHour = parseInt(time.split(':')[0]);
      return timeHour <= currentHour;
    }

    return false;
  };

  // 确认预约
  const confirmBooking = () => {
    if (!state.selectedDate || !state.selectedTime) {
      sheep.$helper.toast('请选择预约时间');
      return;
    }

    // 跳转到订单确认页面
    sheep.$router.go('/pages/order/confirm', {
      data: JSON.stringify({
        items: [
          {
            skuId: state.selectedSku.id || state.coachInfo.id,
            count: 1,
            categoryId: state.coachInfo.categoryId,
            bookingDate: state.selectedDate,
            bookingTime: state.selectedTime,
          },
        ],
        type: 'coach', // 标识为教练预约
      }),
    });
  };

  // 打开营销弹窗
  const onOpenActivity = () => {
    state.showActivityModel = true;
  };

  // 立即领取优惠劵
  const onTakeCoupon = async (id) => {
    const { code } = await CouponApi.takeCoupon(id);
    if (code !== 0) {
      return;
    }
    uni.showToast({
      title: '领取成功',
    });
    setTimeout(() => {
      getCoupon();
    }, 1000);
  };

  const shareInfo = computed(() => {
    if (isEmpty(state.coachInfo)) return {};
    return sheep.$platform.share.getShareInfo(
      {
        title: `预约教练：${state.coachInfo.name}`,
        image: sheep.$url.cdn(state.coachInfo.picUrl),
        desc: state.coachInfo.introduction,
        params: {
          page: SharePageEnum.GOODS.value,
          query: state.coachInfo.id,
        },
      },
      {
        type: 'coach',
        title: state.coachInfo.name,
        image: sheep.$url.cdn(state.coachInfo.picUrl),
        price: fen2yuan(state.coachInfo.price),
      },
    );
  });

  const getCoupon = async () => {
    const { code, data } = await CouponApi.getCouponTemplateList(state.coachId, 2, 10);
    if (code === 0) {
      state.couponInfo = data;
    }
  };

  onLoad((options) => {
    // 非法参数
    if (!options.id) {
      state.coachInfo = null;
      state.skeletonLoading = false;
      return;
    }
    state.coachId = options.id;

    // 生成可预约日期
    generateAvailableDates();

    // 1. 加载教练信息（复用商品接口）
    SpuApi.getSpuDetail(state.coachId).then((res) => {
      if (res.code !== 0 || !res.data) {
        state.coachInfo = null;
        state.skeletonLoading = false;
        return;
      }
      // 加载到教练信息
      state.skeletonLoading = false;
      state.coachInfo = res.data;
      state.selectedSku = res.data.skus?.[0] || {};

      // 加载是否收藏
      if (isLogin.value) {
        FavoriteApi.isFavoriteExists(state.coachId, 'goods').then((res) => {
          if (res.code !== 0) {
            return;
          }
          state.coachInfo.favorite = res.data;
        });
      }
    });

    // 2. 加载优惠劵信息
    getCoupon();
  });
</script>

<style lang="scss" scoped>
.detail-card {
  background-color: #ffffff;
  margin: 14rpx 20rpx;
  border-radius: 16rpx;
  overflow: hidden;
}

// 教练信息卡片
.coach-card {
  .coach-info {
    flex: 1;

    .coach-avatar {
      width: 120rpx;
      height: 120rpx;
      border-radius: 60rpx;
      border: 4rpx solid #f0f0f0;
    }

    .coach-details {
      flex: 1;

      .coach-name {
        font-size: 36rpx;
        font-weight: 600;
        color: #333333;
        margin-bottom: 8rpx;
      }

      .coach-experience {
        font-size: 26rpx;
        color: #666666;
        line-height: 1.4;
        margin-bottom: 8rpx;
      }

      .coach-rating {
        .rating-stars {
          .star-icon {
            font-size: 24rpx;
            color: #ddd;
            margin-right: 4rpx;

            &.active {
              color: #ffa500;
            }
          }
        }

        .rating-text {
          font-size: 24rpx;
          color: #666666;
        }

        .student-count {
          font-size: 24rpx;
          color: #999999;
        }
      }
    }
  }

  .price-box {
    .price-text {
      font-size: 42rpx;
      font-weight: 500;
      color: #ff3000;
      line-height: 30rpx;
      font-family: OPPOSANS;

      &::before {
        content: '￥';
        font-size: 30rpx;
      }
    }

    .price-unit {
      font-size: 24rpx;
      color: #999999;
      margin-top: 4rpx;
    }
  }

  .coach-tags {
    .tag {
      padding: 8rpx 16rpx;
      background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
      color: #ffffff;
      font-size: 22rpx;
      border-radius: 20rpx;
      margin-right: 16rpx;
    }
  }

  .discounts-box {
    .tag {
      flex-shrink: 0;
      padding: 4rpx 10rpx;
      font-size: 24rpx;
      font-weight: 500;
      border-radius: 4rpx;
      color: var(--ui-BG-Main);
      background: var(--ui-BG-Main-tag);
    }

    .discounts-title {
      font-size: 24rpx;
      font-weight: 500;
      color: var(--ui-BG-Main);
      line-height: normal;
    }

    .cicon-forward {
      color: var(--ui-BG-Main);
      font-size: 24rpx;
      line-height: normal;
      margin-top: 4rpx;
    }
  }
}

// 预约按钮
.buy-box {
  .booking-btn {
    width: 428rpx;
    height: 72rpx;
    font-weight: 600;
    font-size: 32rpx;
    border-radius: 40rpx;
    background: linear-gradient(90deg, var(--ui-BG-Main), var(--ui-BG-Main-gradient));
    color: #ffffff;
  }
}

// 预约时间选择弹窗
.time-select-popup {
  background: #ffffff;
  border-radius: 20rpx 20rpx 0 0;
  max-height: 80vh;

  .popup-header {
    border-bottom: 1rpx solid #f0f0f0;

    .popup-title {
      font-size: 32rpx;
      font-weight: 600;
      color: #333333;
    }

    .close-btn {
      font-size: 32rpx;
      color: #999999;
      width: 60rpx;
      height: 60rpx;
      display: flex;
      align-items: center;
      justify-content: center;
    }
  }

  .time-content {
    .date-selector {
      .date-title {
        font-size: 28rpx;
        font-weight: 600;
        color: #333333;
      }

      .date-scroll {
        white-space: nowrap;

        .date-list {
          .date-item {
            flex-shrink: 0;
            width: 120rpx;
            padding: 20rpx 0;
            text-align: center;
            border-radius: 12rpx;
            margin-right: 16rpx;
            transition: all 0.3s ease;

            .date-day {
              font-size: 22rpx;
              color: #999999;
              margin-bottom: 8rpx;
            }

            .date-date {
              font-size: 28rpx;
              font-weight: 500;
              color: #333333;
            }

            &.active {
              background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);

              .date-day,
              .date-date {
                color: #ffffff;
              }
            }
          }
        }
      }
    }

    .time-selector {
      .time-title {
        font-size: 28rpx;
        font-weight: 600;
        color: #333333;
      }

      .time-grid {
        display: grid;
        grid-template-columns: repeat(4, 1fr);
        gap: 16rpx;

        .time-item {
          padding: 20rpx 0;
          text-align: center;
          font-size: 26rpx;
          color: #333333;
          background: #f8f9fa;
          border-radius: 8rpx;
          transition: all 0.3s ease;

          &.active {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: #ffffff;
          }

          &.disabled {
            background: #f0f0f0;
            color: #cccccc;
            cursor: not-allowed;
          }
        }
      }
    }

    .confirm-btn {
      width: 100%;
      height: 88rpx;
      background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
      color: #ffffff;
      font-size: 32rpx;
      font-weight: 600;
      border-radius: 12rpx;
      border: none;

      &:disabled {
        background: #cccccc;
        color: #ffffff;
      }
    }
  }
}

// 预约按钮
.booking-box {
  .booking-btn {
    width: 428rpx;
    height: 72rpx;
    font-weight: 600;
    font-size: 32rpx;
    border-radius: 40rpx;
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    color: #ffffff;
    box-shadow: 0 8rpx 24rpx rgba(102, 126, 234, 0.4);
  }
}
</style>
